<template>
  <div class="container">
    <div class="infinite-container" style="bottom:82px;">
      <div>
        <div
          class="bgwhite doctor-info flex flex_vcenter"
          v-if="selectDoctorAgain"
          @click="selectDoctorAgain"
          v-show="Object.keys(doctor).length > 0"
        >
          <img class="doctor_avatar" v-lazy="doctor.headerUrl" alt />
          <div class="flex_full">
            <div>
              <span class="docName">{{doctor.doctorName}}</span>
              <span class="docTitle">{{doctor.doctorTitle}}</span>
            </div>
            <div class="mt10">
              <span>{{doctor.departmentName}}</span>
            </div>
          </div>
          <div class="t3" v-if="canChooseDoctor">
            更换医生
            <i class="iconfont icon-small-arrow-right t3 v-middle"></i>
          </div>
        </div>
        <div
          class="bgwhite doctor-info flex flex_vcenter"
          v-else
          v-show="Object.keys(doctor).length > 0"
        >
          <img class="doctor_avatar" v-lazy="doctor.headerUrl" alt />
          <div class="flex_full">
            <div>
              <span class="docName">{{doctor.doctorName}}</span>
              <span class="docTitle">{{doctor.doctorTitle}}</span>
            </div>
            <div class="mt10">
              <span>{{doctor.departmentName}}</span>
            </div>
          </div>
          <div class="t3" v-if="canChooseDoctor">
            更换医生
            <i class="iconfont icon-small-arrow-right t3 v-middle"></i>
          </div>
        </div>
        <mu-list v-show="Object.keys(doctor).length <= 0">
          <mu-list-item title="复诊科室">
            <span slot="right">{{selectedMedical.departmentName}}</span>
          </mu-list-item>
          <mu-divider />

          <mu-list-item title="医生" class="citem aitem">
            <select-again-doctor
              slot="right"
              ref="selectDoctorAgain"
              @change="changeDoctor"
              :departmentId="selectedMedical.departmentId"
            />
          </mu-list-item>
          <mu-divider />
        </mu-list>
      </div>

      <div class="mt10"></div>

      <mu-list>
        <mu-list-item title="问诊人" class="aitem">
          <span
            slot="right"
          >{{familyPerson.realname}} {{familyPerson.sexcode | getSex}}</span>
        </mu-list-item>
        <mu-divider />
      </mu-list>

      <mu-list>
        <mu-list-item title="既往就诊" class="aitem">
          <div slot="right" class="text-right">
            <!-- <p>{{selectedMedical.visitTime.slice(0,11)}}</p> -->
            <p>{{selectedMedical.hospitalName}}/{{selectedMedical.departmentName}}</p>
          </div>
        </mu-list-item>
        <mu-divider />
      </mu-list>

      <mu-list>
        <mu-list-item title="确诊诊断" class="aitem">
          <span slot="right" class="diagnosis" >{{selectedMedical.diagnosisName | safeSlice(20)}}</span>
        </mu-list-item>
        <mu-divider />
      </mu-list>

      <mu-list>
        <mu-list-item title="所需药品" class="aitem" @click="showSelDrugPopup = true">
          <div class="color-subtext" slot="right">
            添加药品
            <i class="iconfont icon-small-arrow-right t3 v-middle"></i>
          </div>
        </mu-list-item>
        <mu-list-item v-if="drugItem && drugItem.filter(v => v.sel === true).length > 0">
          <ul class="drugs flex">
            <template v-for="(value, index) in drugItem">
              <li v-if="value.sel" :key="index">
                {{ value.drugName }}
                <img
                  src="../../assets/images/common_icon_del.png"
                  alt
                  @click="deleteDrugItem(index)"
                />
              </li>
            </template>
          </ul>
        </mu-list-item>
      </mu-list>
      <div class="mt10"></div>
      <left-border-title :title="'病情描述'" :isImportant="true"></left-border-title>
      <div class="textFieldStyle">
        <mu-text-field
          hintText="请描述病情症状，目前是否好转，想要获得医生什么帮助，最少输入5个字"
          multiLine
          :rows="3"
          :rowsMax="3"
          fullWidth
          hintTextClass="hintTextStyle"
          v-model="diseaseDes"
        />
      </div>
      <div class="mt10"></div>
      <left-border-title :title="'病情照片'"></left-border-title>
      <div class="textFieldStyle">
        <ul class="fileHandler flex wrap">
          <li v-for="(item,index) in fileList" :key="index">
            <img :src="item.src" alt />
            <div @click="uploader&&uploader.delFile(index)"></div>
          </li>
          <li v-show="fileList.length < 6">
            <input
              multiple="multiple"
              type="file"
              name="upload"
              id="avatar_load"
              ref="upload1"
              @change="uploader&&(uploader.fileChange(6))"
              accept="image/*"
            />
            <img src="../../assets/images/icon_add_img.png" alt />
          </li>
        </ul>
        <p class="hintTextStyle">请上传病情照片，若为皮肤问题，建议对准患处拍摄。照片仅自己和医生可见（最多6张）</p>
      </div>
    </div>
    <div class="fixed-bottom" style="height:82px;">
      <div class="flex pd10">
        <i class="popupRadio" :class="{iconOk: checkReadme}" @click="checkReadme = !checkReadme"></i>
        <span>
          我已阅读并确认
          <span class="selcolor" @click="goRead()">《知情同意书》</span>
        </span>
      </div>
      <mu-raised-button class="submit-btn" label="提 交" fullWidth primary @click="submit"></mu-raised-button>
    </div>

    <!-- 药品弹窗 -->
    <popup :show="showSelDrugPopup" :popupStyle="{}" @hidePopup="closePopup()">
      <div class="popupContent">
        <div class="popupTitle flex flex_vcenter flex_between">
          <h3>请选择本次所需的药品（供医生参考）</h3>
          <img src="../../assets/images/ic_popup_close.png" alt @click="closePopup()" />
        </div>
        <p class="line"></p>
        <ul class="drugItems">
          <li
            class="flex flex_between flex_vcenter"
            v-for="(value, index) in selectedMedical.drugItem"
            :key="index"
            @click="value.sel = !value.sel"
          >
            <p>{{value.drugName}} {{value.specifiation}}</p>
            <i class="popupRadio" :class="{iconOk: value.sel}"></i>
          </li>
        </ul>
        <div class="flex bottomHandler flex_between">
          <button class="medicalAgainBtn medicalAgainBtn-empty" @click="closePopup()">取消</button>
          <button class="medicalAgainBtn medicalAgainBtn-color" @click="confirmPopup()">确定</button>
        </div>
      </div>
    </popup>
    <mu-dialog
      title="警告"
      width="600"
      max-width="80%"
      :esc-press-close="false"
      :overlay-close="false"
      :open.sync="openAlert"
    >
      复诊医院缺少您所需的
      <i v-for="(item, index) in emptyList" :key="index">{{item}}</i>，是否需要更换医院？
      <br />若同意医生根据病情调整药品，请选择继续提交！
      <div slot="actions" flat>
        <select-again-doctor
          slot="right"
          ref="selectDoctorAgain"
          @change="changeDoctor"
          :departmentCode="selectedMedical.departmentCode"
          :showText="'更换医院'"
          @click="closeAlertDialog()"
        />
      </div>
      <i
        slot="actions"
        flat
        color="primary"
        @click="closeAlertDialog(true)"
        style="font-style: normal;color: #999;font-weight: 500;"
      >继续提交</i>
    </mu-dialog>
  </div>
</template>

<script>
import leftBorderTitle from "../../components/leftBorderTitle.vue";
import iconTest from "../../assets/hzssyy/icon_qdqh.png";
import Uploader from "../../components/Uploader.js";
import SelectAgainDoctor from "@/components/SelectAgainDoctor";
import popup from "../../components/BsPopup.vue";
import { commonAjaxJson, RESTFUL_API } from "@/api/api";

export default {
  data() {
    return {
      selectedMedical: JSON.parse(sessionStorage.selectedMedical || "{}"),
      drugItem: JSON.parse(sessionStorage.selectedMedicalItem || "[]"),
      familyPerson: JSON.parse(sessionStorage.getItem("familyPerson")) || {},
      diseaseDes: sessionStorage.getItem("medicalAgainDiseaseDescribe") || "",
      doctor: {},
      uploader: null,
      fileList: [],
      param: {},
      showSelDrugPopup: false,
      checkReadme: false,
      canChooseDoctor: true,
      openAlert: false,
      emptyList: [],
      continueFlag: false
    };
  },
  components: {
    popup,
    leftBorderTitle,
    SelectAgainDoctor
  },
  mounted() {
    this.uploader = new Uploader(this.fileList, this.$refs.upload1);
    if (this.$route.query.name) {
      this.doctor = this.$route.query;
      this.$store.commit("UPDATE_PAGEDATA", this.doctor);
    }
    if (sessionStorage.getItem("medicalAgainDoctor")) {
      this.canChooseDoctor = false;
      this.doctor = JSON.parse(sessionStorage.getItem("medicalAgainDoctor"));
    }
  },
  methods: {
    goRead() {
      // this.checkReadme = true;
      // this.$store.commit("showTips");
      this.$router.push("/protocal?key=OR_informed_consent");
    },
    openSelDoctorPage() {
      // 打开选择医生页面
      this.$refs.selDoctor.showPop();
    },
    go(path) {
      if (this.diseaseDes.length > 0) {
        sessionStorage.setItem("medicalAgainDiseaseDescribe", this.diseaseDes);
      }
      this.$router.push(path);
    },
    changeDoctor(d) {
      this.doctor = d;
      this.$store.commit("UPDATE_PAGEDATA", d);
    },
    selectDoctorAgain() {
      this.$refs.selectDoctorAgain.getFillDoctors();
    },
    selectDoctor() {
      this.$router.replace(
        `/medicalAgain/selDoctor?departmentCode=${this.selectedMedical.departmentCode}`
      );
    },
    closePopup() {
      this.selectedMedical = JSON.parse(sessionStorage.selectedMedical || "{}");
      this.showSelDrugPopup = false;
    },
    deleteDrugItem(index) {
      this.drugItem[index].sel = false;
      this.selectedMedical.drugItem[index].sel = false;
      sessionStorage.setItem(
        "selectedMedical",
        JSON.stringify(this.selectedMedical)
      );
    },
    confirmPopup() {
      let drugItem = this.selectedMedical.drugItem.map(v => {
        // return v
        if (v.sel === true) {
          return {
            drugName: v.drugName,
            frequency: v.frequency,
            onesDose: v.onesDose,
            quantity: v.quantity,
            sel: v.sel,
            specifiation: v.specifiation,
            usage: v.usage
          };
        } else {
          return {};
        }
      });
      sessionStorage.setItem(
        "selectedMedical",
        JSON.stringify(this.selectedMedical)
      );
 
      this.drugItem = drugItem;
      this.showSelDrugPopup = false;
    },
    submit() {
      if (!this.doctor.doctorName) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请选择医生!"
        });
        return;
      }
      if (this.diseaseDes.length < 5) {
        this.$store.commit("UPDATE_TOAST", {
          message: "病情描述不能少于5个字!"
        });
        return;
      }
      if (!this.checkReadme) {
        this.$store.commit("UPDATE_TOAST", {
          message: "请阅读并确认《知情同意书》"
        });
        return;
      }
      this.uploader.doUpLoad().then(v => {
        var imgids = v && v[0];
        const person = this.familyPerson;
        const uid = (person && person.id) || "";
        const D = this.doctor;
        const M = this.selectedMedical;
        this.param = {
          hospitalCode: sessionStorage.hospitalCode,
          fileIds: imgids || "",
          visitNo: M.visitNo,
          patientCode: person.patientcode || person.patientCode,
          diagnosisName: M.diagnosisName || "",
          departmentCode: D.departmentCode,
          doctorCode: D.doctorCode || "",
          departmentId: D.departmentId,
          departmentName: D.departmentName,
          doctorId: D.doctorId || "",
          doctorName: D.doctorName,
          doctorJobTitle: D.doctorTitle,
          question: this.diseaseDes,
          consultUserId: uid,
          personName: person.realname,
          gender: person.sexcode,
          orgCode: "",
          medInsurance: M.isMedInsurance,
          cost: D.returnVisitFee,
          drugs: "",
          userId: sessionStorage.getItem("userId")
        };

        // 转换药品名称
        if (this.drugItem && this.drugItem.length > 0) {
          for (let i in this.drugItem) {
            if (this.drugItem[i].sel === true) {
              this.param.drugs += this.drugItem[i].drugName + ",";
            }
          }
        }

        this.param.drugs = this.param.drugs.slice(0, this.param.drugs.length - 1);

        // 检查药品是否存在
        let drugList = []
        this.drugItem.forEach(v => {
          drugList.push({
            orgDrugId: v.drugId,
            orgFactoryId: v.factoryId
          })
        })
        let prescriptionList = [{
          drugList
        }]
        commonAjaxJson(RESTFUL_API.checkDrug, {
          hospitalCode:sessionStorage.hospitalCode,
          prescriptionList
        }, true).then(res => {
          const {code, data} = res.data
          
          if (code == 200 && !data.flag) {
            this.emptyList = data.noExistDrugName;
            this.openAlertDialog();
            if (!this.continueFlag) {
              return;
            }
          }

          // 提交复诊配药
          commonAjaxJson(RESTFUL_API.saveDispenseOrder, this.param, true).then(
            res => {
              if (res.data.code == 200) {
                const query = Object.assign(res.data.data, {
                  doctorCode: D.doctorCode
                });
                let illPayType = "";
                if (M.isMedInsurance == 1) {
                  illPayType = "medInsurance";
                } else {
                  illPayType = "selfPay";
                }
                sessionStorage.setItem("illPayType", illPayType);
                this.$router.push({
                  path: "/medicalAgain/confirmPay",
                  query: {
                    cid: res.data.data.consultId,
                    doctorCode: D.doctorCode
                  }
                });
              }
            }
          );
        });
      });
    },
    openAlertDialog() {
      this.openAlert = true;
    },
    closeAlertDialog(flag) {
      if (flag) {
        this.continueFlag = true;
        this.submit();
      }
      this.openAlert = false;
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === "/protocal") {
      from.meta.keepAlive = true;
    } else {
      from.meta.keepAlive = false;
    }
    this.$store.commit("hideTips");
    next();
  }
};
</script>

<style scoped lang="less">
@import "../../common/css/flex.css";
@import "../../common/css/component";
.popupRadio {
  width: 20px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #c5c8d0;
  margin-right: 5px;
}
.iconOk {
  background-image: url("../../assets/images/iconfont-ok-checked.png");
  background-repeat: no-repeat;
  background-size: contain;
  border: 1px solid #4fbb6c;
}
.drugs {
  li {
    position: relative;
    background-color: #e7f9f2;
    color: @color-primary;
    border-radius: 3px;
    margin-right: 20px;
    padding: 5px 10px;
  }
  img {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 16px;
    height: 16px;
  }
}
.infinite-container {
  @{deep} .mu-list {
    background: #fff;
  }
  @{deep} .mu-item-title {
    color: #666;
    font-size: 14px;
  }
  @{deep} .mu-item-right {
    color: #333;
    justify-content: flex-end;
  }
  .t3 {
    color: #cdcdcd;
  }
}
.doctor-info {
  color: #333;
  padding: 10px;
  img {
    width: 80px;
    height: 80px;
    margin: 0 10px;
  }
  .doctor_avatar {
    border-radius: 50%;
  }
  .docName {
    font-size: 16px;
    font-weight: bold;
  }
  .docTitle {
    font-size: 12px;
    color: #f60;
    border: 1px solid #f60;
    border-radius: 16px;
    padding: 0 3px;
  }
}
.citem {
  @{deep} .mu-item-title {
    color: #323232;
  }
}

.aitem {
  @{deep} .mu-item-right {
    right: 8px;
  }
}

.textFieldStyle {
  background-color: white;
  border-top: 1px solid @color-border;
  padding: 10px 20px;
  @{deep} .mu-text-field-hint {
    white-space: pre-wrap;
    line-height: 1.5;
    font-size: 14px;
    margin-top: -18px;
  }
}

.hintTextStyle {
  white-space: pre-wrap;
  color: rgba(0, 0, 0, 0.38);
}

.fileHandler {
  padding: 10px 0;
  li {
    position: relative;
    width: 80px;
    height: 80px;
    margin: 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    input {
      opacity: 0;
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
    }
    img {
      width: 80%;
      height: 80%;
    }
  }
  > li:not(:last-child) {
    > div {
      position: absolute;
      top: -5px;
      right: -5px;
      width: 20px;
      height: 20px;
      background: url("../../assets/wzjl/icon_del_img.png") no-repeat center
        center/20px 20px;
    }
  }
}

.addBtn {
  border: 1px dotted #7e7e7e;
  position: absolute;
  width: 80px;
  height: 80px;
  top: 0;
  left: 0;
  color: #7e7e7e;
  line-height: 60px;
  text-align: center;
  font-size: 60px;
}

.chose {
  color: #ccc;
  font-size: 14px;
}

.davatar {
  width: 20px;
  height: 20px;
  margin-right: 6px;
}

.longBtnC {
  padding: 20px 30px;
}

.selcolor {
  color: #29bc6c;
}
.diagnosis {
  // max-width: 60%;
  text-align: right;
}
.medlist {
  padding: 0px 12px 10px 15px;
  background: #fff;
  width: 100%;
  dl {
    padding: 0;
    margin: 0;
    position: relative;
    width: 100%;
  }
  dt {
    width: 100%;
    min-height: 44px;
    display: table;
    padding: 10px 0;
    > span {
      display: table-cell;
      vertical-align: middle;
      color: #666;
    }
    > div {
      color: #333;
      display: table-cell;
      vertical-align: middle;
      text-align: right;
      padding-right: 24px;
      position: relative;
      > i {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        right: 0px;
      }
    }
  }
  dd {
    width: 100%;
    padding: 0;
    margin: 0;
    ul {
      width: 100%;
      > li:last-child {
        padding-bottom: 0px;
      }
      > li:first-child {
        padding-top: 12px;
      }
      > li {
        padding: 6px 0px 6px 0px;
        width: 100%;
        display: table;
        > div {
          display: table-cell;
          color: #999;
          font-size: 12px;
          > div + div {
            padding-top: 2px;
          }
        }
        > div:first-child {
          > div:first-child {
            color: #666;
            font-size: 14px;
          }
        }
        > div:nth-child(2) {
          color: #999;
          text-align: right;
          white-space: nowrap;
        }
      }
    }
  }
}
.popupContent {
  .drugItems {
    > li {
      border-bottom: 1px solid #f7f7f7;
      padding: 10px;
    }
  }
  .bottomHandler {
    button {
      width: 46%;
    }
    padding: 10px;
  }
  .popupRadio {
    width: 20px;
    height: 20px;
    border-radius: 10px;
    border: 1px solid #c5c8d0;
  }
  .iconOk {
    background-image: url("../../assets/images/iconfont-ok-checked.png");
    background-repeat: no-repeat;
    background-size: contain;
    border: 1px solid #4fbb6c;
  }
  background-color: white;
  .popupTitle {
    padding: 14px;
    img {
      width: 18px;
      height: 18px;
    }
  }
  .line {
    border-top: 1px solid #f7f7f7;
    margin: 0 10px;
  }
}
</style>
